#coding: utf8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
import redis

import logging
import logging.config

from exceptions import Exception

logging.config.fileConfig('./conf/log.conf')
rlog = logging.getLogger('root')

"""
交易状态。可选值: * TRADE_NO_CREATE_PAY(没有创建支付宝交易) * WAIT_BUYER_PAY(等待买家付款) * WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款) * WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货) * TRADE_BUYER_SIGNED(买家已签收,货到付款专用) * TRADE_FINISHED(交易成功) * TRADE_CLOSED(付款以后用户退款成功，交易自动关闭) * TRADE_CLOSED_BY_TAOBAO(付款以前，卖家或买家主动关闭交易)
"""

trade_status_weight = {
    'TRADE_NO_CREATE_PAY' : 2,
    'WAIT_BUYER_PAY': 2,
    'WAIT_SELLER_SEND_GOODS': 8,
    'WAIT_BUYER_CONFIRM_GOODS': 9,
    'TRADE_BUYER_SIGNED': 9,
    'TRADE_FINISHED': 10,
    'TRADE_CLOSED': 10,
    'TRADE_CLOSED_BY_TAOBAO': 1,
}

non_finish_trade_status = set(
    ['TRADE_NO_CREATE_PAY', 'WAIT_BUYER_PAY', 'TRADE_CLOSED_BY_TAOBAO']        
)


def get_trades_time(trade):
    if 'pay_time' in trade:
        return trade['pay_time']
    if 'modified' in trade:
        return trade['modified']
    return trade['created']

def cal_trade_time_weight(trade):
    try:
        timestamp = time.strptime(get_trades_time(trade), '%Y-%m-%d %H:%M:%S' ) #2011-10-17 21:38:51)
        timestamp = time.mktime(timestamp)
    except Exception as e:
        rlog.warning('calculate trade time weight fail: %s' %(repr(e)))
        return 0
    time_interval = 1 + (time.time() - timestamp) / 86400 # days from list items
    w = 1000/time_interval
    return w

def cal_trade_weight(trade):
    w_time = cal_trade_time_weight(trade)
    w = w_time * trade_status_weight[trade['status']]
    return w

def cal_order_trade_weight(trade, rdb):
    w = cal_trade_weight(trade)
    for order in trade['orders']['order']:
        rdb.zincrby(trade['seller_nick'], order['num_iid'], w)
        if trade['status'] == 'TRADE_FINISHED':
        #if trade['status'] not in non_finish_trade_status:
            rlog.debug( 'rincrby parameter: %s, %s, %d, %s' %('ordernum:'+trade['seller_nick'], str(order['num_iid']), int(order['num']), trade['status']) )
            rdb.hincrby('ordernum:'+trade['seller_nick'], str(order['num_iid']), int(order['num']))
            rlog.debug('sadd parameter: %s, %d, %s' %('orders:'+str(order['num_iid']), order['oid'], trade['status']))
            rdb.sadd('orders:'+str(order['num_iid']), order['oid'])

def trades_rec(nick, mdb, rdb):
    cur = mdb.trades.find({'seller_nick':nick})
    for i in cur:
        try:
            cal_order_trade_weight(i, rdb)
        except Exception as e:
            rlog.warning('cal_order_trade_weight fail, tid[%s]: %s' %(repr(i['_id']), repr(e)))


def testing_trades_weight(nick):
    m = pymongo.Connection('127.0.0.1:57324')
    rdb = redis.StrictRedis(host='127.0.0.1', port=56379, db=9)
    rdb.delete(nick, 'ordernum:'+nick)
    trades_rec(nick, m.taogold, rdb)
    res = rdb.zrange(nick, 0, -1, desc=True, withscores=True)
    for i in res:
        num_iid, scores = i
        print num_iid, scores, rdb.scard('orders:'+num_iid), rdb.hget('ordernum:'+nick, num_iid)


if __name__ == '__main__':
    testing_trades_weight('古代')
    





